package cn.jhc.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.jhc.bean.Study;
import cn.jhc.dao.StudyDao;
import cn.jhc.util.HibernateUtil;

public class StudyDaoImpl implements StudyDao {
	private static final Logger LOG = Logger.getLogger(StudyDaoImpl.class.getName());
	
	@Override
	public void save(Object o) {
		if (o instanceof Study) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("保存失败,请传入" + Study.class.getName() + "的实例对象。");
		
	}

	@Override
	public void update(Object o) {
		if (o instanceof Study) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.update(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("更新失败,请传入" + Study.class.getName() + "的实例对象。");
	}

	@Override
	public void delete(Object o) {
		if(o instanceof Study) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.delete(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("删除失败,请传入" + Study.class.getName() + "的实例对象。");
	}

	@Override
	public Object get(int id) {
		Study study = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		study = session.get(Study.class, id);
		session.getTransaction().commit();
		
		return study;
	}

	@Override
	public List list() {
		List<Study> studies = null;
		String hql = "from Study";
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		studies = query.list();
		session.getTransaction().commit();
		return studies;
	}

	@Override
	public List list(int start, int count) {
		List<Study> studies = null;
		String hql = "from Study";
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(start + count);
		studies = query.list();
		session.getTransaction().commit();
		return studies;
	}

	@Override
	public long getCount() {
		String hql = "select count(s.teachid) from Study s";
		Long count = 0l;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		count = (Long) query.uniqueResult();
		session.getTransaction().commit();
		
		return count;
	}

}
